
%% Background subtraction Methods

%% Main Function
function im = Background_Subtruction(subtype,a,b,c)
    if(strcmp(subtype,'BASIC')) 
        im = im_sub(a,b);
        im = Threashhold(a,im);
    elseif(strcmp(subtype,'M_BASIC')) 
        im = im_Bsub(a,b);
    elseif(strcmp(subtype,'MEDIAN'))
        im = Median_sub(a,b,c);
    elseif(strcmp(subtype,'GAUSSIAN'))
        im = Gaussian_sub('GAUSSIAN',a,b,c);
    end
end

%% Subfunctions
function imOut = Threashhold(a,im)
    mean_ML = mean(mean(im));
    tmp_data = a - mean_ML;
    var_ML = mean(mean(tmp_data.^2));
    im_s = size(im);
    
   imOut = zeros(im_s);
   for i = 1:im_s(1)
        for j = 1:im_s(2)
            if im(i,j) > mean_ML + sqrt(var_ML)*0.5
                imOut(i,j) = im(i,j);
            end
        end
   end
end

function im = Median_sub(a,b,c)
    est_BackGround = median(b,3);
    im = imsubtract(est_BackGround,a);
    im = im(:,:) > c;
end

function im = Gaussian_sub(subtype,a,b,c)

    a = double(a);
    a_size = size(a);
    im = zeros(a_size);
    for i = 1:a_size(1)
        for j = 1:a_size(2)
            im(i,j) = log(1/(2*pi)^(1/2)*1/b(i,j,2)^(1/2)*exp(-1/2*(a(i,j)-b(i,j,1))^2*b(i,j,2)));
        end
    end
    
end

function im = im_sub(a,b)
    a = double(a);
    b = double(b);
    
    im = abs(a-b);
end

function im = im_Bsub(a,b)
    a = double(a);
    b = double(b);
    
    im = (a-b);
end